# -*- coding: utf8 -*-
"""
Created by Leon on 2015/10/5.
"""
import json
import urlparse
import urllib2
from datetime import datetime, timedelta

from aliyunsdkcore import client
from aliyunsdkrds.request.v20140815 import DescribeBackupsRequest, CreateBackupRequest
from oss.oss_api import *

endpoint = "oss-cn-shanghai.aliyuncs.com"
bucket = "********"
access_key_id = "************"
access_key_secret = "***************"
db_instance_id = "***********"


def create_backup(clt, db_instance_id):
    request = CreateBackupRequest.CreateBackupRequest()
    request.set_DBInstanceId(db_instance_id)
    request.set_accept_format("json")
    result = clt.do_action(request)
    return result


def fetch_backup_download_url(clt, start_time, end_time, db_instance_id):
    time_format = "%Y-%m-%dT%H:%MZ"
    request = DescribeBackupsRequest.DescribeBackupsRequest()
    request.set_DBInstanceId(db_instance_id)
    request.set_StartTime(start_time.strftime(time_format))
    request.set_EndTime(end_time.strftime(time_format))
    request.set_accept_format('json')
    backup_result = clt.do_action(request)
    backup_items = json.loads(backup_result)['Items']['Backup']
    urls = [item['BackupDownloadURL'] for item in backup_items]
    return urls


def parse_filename_from_url(url):
    return urlparse.urlparse(url).path[1:]


def upload_to_oss(oss, bucket, url):
    filename = parse_filename_from_url(url)
    file_content = urllib2.urlopen(url, timeout=10).read()
    res = oss.put_object_from_string(bucket, filename, file_content)
    if res.status == 200:
        return True


def main():
    clt = client.AcsClient(access_key_id, access_key_secret, "cn-hangzhou")
    create_backup(clt, db_instance_id)
    print "备份成功，正在上传"
    oss = OssAPI(endpoint, access_key_id, access_key_secret)

    end_time = datetime.now()
    start_time = end_time - timedelta(hours=24)
    urls = fetch_backup_download_url(clt, start_time, end_time, db_instance_id)
    for url in urls:
        if upload_to_oss(oss, bucket, url):
            print "上传成功"


if __name__ == '__main__':
    main()
